package com.example.test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    //蓝牙权限
    public static final int REQUEST_OPEN_BT_CODE = 0x01;
    private BleHelp bleHelp = BleHelp.getInstance();
    private Button send_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send_btn = findViewById(R.id.send_btn);
        initPermission();
        bleHelp.init(this, new BleHelp.BleCallback() {
            @Override
            public void connectSuccess() {
                send_btn.setEnabled(true);
            }

            @Override
            public void getDeviceReturnData(byte[] data) {

            }

            @Override
            public void error(int e) {

            }
        });
        String macPath = this.getBtAddressByReflection();
        System.out.println("macPath=============" + macPath);
    }

    public void start(View view) {
        bleHelp.setMacAndUuids("54:6C:0E:35:78:18",
                "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
                "6e400003-b5a3-f393-e0a9-e50e24dcca9e",
                "6e400003-b5a3-f393-e0a9-e50e24dcca9e",
                "00002902-0000-1000-8000-00805f9b34fb");
        bleHelp.start();
    }

    public void stopCon(View view) {
        bleHelp.stopCon();
    }

    public void sendData(View view) {
        String data = "123456";
        bleHelp.sendDataToDevice(data.getBytes(StandardCharsets.UTF_8));
    }

    public void jumpToBlue(View vie) {
        startActivity(new Intent(this, BlueToothActivity.class));
    }

    public String getBtAddressByReflection() {
        //获取已绑定设备信息和连接状态
        Set<BluetoothDevice> deviceList = bleHelp.getBluetoothAdapter().getBondedDevices();
        for (BluetoothDevice device : deviceList) {
            Log.d("Jason", "Name:" + device.getName() + "   Mac:" + device.getAddress());
            try {
                //使用反射调用获取设备连接状态方法
                Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                isConnectedMethod.setAccessible(true);
                boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                Log.d("Jason", "isConnected：" + isConnected + "   Mac:" + device.toString());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_OPEN_BT_CODE);
            } else {
                showToast("已经有权限了！");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_OPEN_BT_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//蓝牙权限开启成功
                showToast("蓝牙权限已开启");
            } else {
                showToast("蓝牙权限未开启,请设置");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
